package com.hxh.config;

import com.hxh.entity.ProjectConfigRecord;
import com.hxh.entity.output.ApiResult;
import com.hxh.service.ProjectConfigRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.util.List;

@ControllerAdvice
public class ResponseEnhancer implements ResponseBodyAdvice<ApiResult> {
    @Autowired
    ProjectConfigRecordService projectConfigRecordService;

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return returnType.getParameterType().equals(ApiResult.class);
    }

    @Override
    public ApiResult beforeBodyWrite(ApiResult body, MethodParameter returnType, MediaType selectedContentType,
                                     Class<? extends HttpMessageConverter<?>> selectedConverterType,
                                     ServerHttpRequest request, ServerHttpResponse response) {

        if (body != null) {
            List<ProjectConfigRecord> records = projectConfigRecordService.getAllChangedRecord();
            body.setProjectConfigRecord(records);
        }
        return body;
    }
}
